package com.ljqc.sbom.management.util;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Objects;

/**
 * bean copy util
 */
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class BeanCopyUtils {

    public static <S, T> List<T> copyList(Collection<S> sourceList, Class<T> targetType) {
        if (Objects.isNull(sourceList)) {
            return null;
        }
        List<T> newList = new ArrayList<>();
        if (CollectionUtils.isEmpty(sourceList)) {
            return newList;
        }
        for (S s : sourceList) {
            if (Objects.nonNull(s)) {
                T t = BeanUtils.instantiateClass(targetType);
                BeanUtils.copyProperties(s, t);
                newList.add(t);
            } else {
                newList.add(null);
            }
        }
        return newList;
    }

    public static <S, T> T copy(S source, Class<T> targetType) {
        if (Objects.isNull(source)) {
            return null;
        }
        T t = BeanUtils.instantiateClass(targetType);
        BeanUtils.copyProperties(source, t);
        return t;
    }

}
